import React, { Component } from "react";
import { Select } from "antd";
import TheTable from "../../../components/TheTable";
import TheButton from "../../../components/TheButton";
import TheImage from "../../../components/TheImage";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from "../../../components/TheQueryForm";
import TheTableExtend from "@/components/TheTableExtend";
import {
  apiGetBrandinfoList,
  apiGetGoodsClassifyTree,
} from "@/request/mallManagement";
import {
  apiAppBrandInfoAdd,
  apiAppBrandInfoPage,
  apiAppBrandInfoDel,
  apiAppBrandInfoEdit,
  apiAppBrandInfoFlag,
} from "@/request/app/appBrandInfo";
const { Option } = Select;
class AppBrandInfo extends Component {
  constructor() {
    super();
    this.queryFormRef = React.createRef();
    this.formRef = React.createRef();
    this.state = {
      title: "新增",
      loading: false,
      dataSource: [],
      columns: [
        {
          title: "品牌名称",
          dataIndex: "brandName",
          key: "brandName",
        },
        {
          title: "品牌图片",
          dataIndex: "brandImg",
          key: "brandImg",
          render: (text, record) => {
            return <TheImage width={270} height={106} src={record.brandImg} />;
          },
        },
        // {
        //   title: "所属类目",
        //   dataIndex: "brandClassifyName",
        //   key: "brandClassifyName",
        // },
        {
          title: "排序",
          dataIndex: "sorted",
          key: "sorted",
        },
        {
          title: "状态",
          render: (text, render) => {
            let label = "";
            switch (render.appBrandState) {
              case "0":
                label = "不启用";
                break;
              case "1":
                label = "启用";
                break;
              default:
                label = "返回值错误";
            }
            return label;
          },
        },
        {
          title: "最近一次操作时间",
          dataIndex: "updateTime",
          key: "updateTime",
        },
        {
          title: "操作",
          render: (text, render) => {
            return (
              <>
                <TheButton haspermi={['app:brand:edit']} onClick={() => this.edit(render)}>
                  修改
                </TheButton>
                <TheButton haspermi={['app:brand:del']} onClick={() => this.del(render)}>
                  删除
                </TheButton>
                {render.appBrandState === "0" && (
                  <TheButton
                    haspermi={["app:brand:on"]}
                    onClick={() =>
                      this.putawayClick(
                        render.appBrandId,
                        render.brandId,
                        "1",
                        "开启"
                      )
                    }
                  >
                    开启
                  </TheButton>
                )}
                {render.appBrandState === "1" && (
                  <TheButton
                    haspermi={["app:brand:off"]}
                    onClick={() =>
                      this.putawayClick(
                        render.appBrandId,
                        render.brandId,
                        "0",
                        "关闭"
                      )
                    }
                  >
                    关闭
                  </TheButton>
                )}
              </>
            );
          },
        },
      ],
      newColumns: [],
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      brandList: [],
      brandInfo: {},
      isModalOpen: false,
      form_show: true,
      searchOption: [
        {
          field: "brandName",
          label: "品牌名",
          placeholder: "请输入",
          required: false,
          rules: [],
          type: "Input",
          defaultValue: "",
        },
        {
          field: "appBrandState",
          label: "状态",
          placeholder: "请选择状态",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { label: "所有", value: "" },
            { label: "开启", value: "1" },
            { label: "未开启", value: "0" },
          ],
          defaultValue: "",
        },
      ],
      queryForm: {},
      isEdit: false,
      classifyList: [],
    };
  }
  putawayClick = (appBrandId, brandId, appBrandState, text) => {
    React.$confirm({
      title: `您确认${text}此品牌吗？`,
      onOk: async () => {
        let res = await apiAppBrandInfoFlag({
          appBrandId,
          brandId,
          appBrandState,
        });
        if (res.code === 0) {
          React.$message({
            type: "info",
            content: `品牌${text}成功`,
          });
          this.getData();
        }
      },
    });
  };
  async componentDidMount() {
    this.getData();
    this.getClassifyList();
    this.onColumnsFilter(this.state.columns);
  }
  async getClassifyList() {
    const res = await apiGetGoodsClassifyTree();
    if (res.code === 0) {
      this.setState({
        classifyList: res.data.map((v) => {
          return {
            value: v.value,
            label: v.label,
            children: v.children.length > 0 ? v.children : [],
          };
        }),
      });
    }
  }
  classifyChange = (e) => {
    this.getBrandList(e[e.length - 1]);
  };
  async getBrandList(e) {
    let res = await apiGetBrandinfoList({ brandClassifyId: e });
    if (res.code === 0) {
      if (this.formRef.current && !this.state.isEdit) {
        this.formRef.current.setFieldsValue({
          brandId: "",
        });
      }

      this.setState({
        brandList: res.data,
      });
    }
  }
  getData(values) {
    this.setState(
      {
        queryForm: values === undefined ? this.state.queryForm : { ...values },
      },
      async () => {
        const { pageNo, pageSize } = this.state.pageData;
        const { queryForm } = this.state;
        const res = await apiAppBrandInfoPage({
          pageNo,
          pageSize,
          ...queryForm,
        });
        if (res.code === 0) {
          this.setState({
            dataSource: res.data,
            total: res.totalCount,
          });
        }
      }
    );
  }
  add() {
    // this.setState({
    //   isEdit: false,
    //   isModalOpen: true,
    //   title: "新增",
    // });
    this.props.history.push(`/app/brand/edit/${0}`);
  }
  handleOk = async () => {
    const values = this.formRef.current.getFieldsValue();
    const {
      brandName,
      brandImg,
      brandId,
      goodsClassifyName,
      brandClassifyName,
    } = this.state.brandInfo;
    console.log(this.state.brandInfo);
    if (this.state.isEdit) {
      const res = await apiAppBrandInfoEdit({
        brandId,
        ...values,
        brandName: brandName,
        brandImg,
        brandClassifyName,
      });
      if (res.code === 0) {
        this.handleCancel();
        this.pageChange(1, 10);
      }
    } else {
      const res = await apiAppBrandInfoAdd({
        ...values,
        brandName: brandName,
        brandImg,
        brandClassifyName: goodsClassifyName,
      });
      if (res.code === 0) {
        this.handleCancel();
        this.pageChange(1, 10);
      }
    }
  };
  handleCancel = () => {
    this.formRef.current.resetFields();
    this.setState({
      isModalOpen: false,
      brandList: [],
    });
  };
  async edit(row) {
    // await this.classifyChange(row.appBrandId);
    // this.setState(
    //   {
    //     isEdit: true,
    //     isModalOpen: true,
    //     title: "编辑",
    //     brandInfo: { ...row },
    //   },
    //   () => {
    //     this.formRef.current.setFieldsValue({
    //       brandClassifyId: row.brandClassifyId.split(","),
    //       brandId: row.brandId,
    //       brandImg: row.brandImg,
    //       sorted: row.sorted,
    //     });
    //   }
    // );
    this.props.history.push(`/app/brand/edit/${row.appBrandId}`);
  }
  del = (record) => {
    React.$confirm({
      title: "警告",
      content: `确定删除此信息吗？`,
      onOk: async () => {
        const res = await apiAppBrandInfoDel({
          brandId: record.brandId,
          appBrandId: record.appBrandId,
        });
        if (res.code === 0) {
          this.pageChange(1, 10);
        }
      },
    });
  };
  pageChange = (pageNo, pageSize) => {
    console.log(pageNo, pageSize);
    this.setState(
      {
        pageData: {
          pageNo,
          pageSize,
        },
      },
      () => {
        this.getData();
      }
    );
  };
  onTableRefresh() {
    this.getData();
  }
  onColumnsFilter(value) {
    this.setState({
      newColumns: value,
    });
  }
  brandChange(e) {
    const { brandList } = this.state;
    this.setState({
      brandInfo: brandList.find((item) => item.brandId === e),
    });
  }
  onReset() {
    this.setState(
      {
        queryForm: {},
      },
      () => {
        this.pageChange(1, 10);
      }
    );
  }
  render() {
    const {
      loading,
      dataSource,
      columns,
      pageData,
      total,
      newColumns,
      form_show,
      searchOption,
    } = this.state;
    const { pageNo, pageSize } = pageData;
    return (
      <div className={"p-layout-box configuration"}>
        <TheQueryForm
          ref={(ref) => (this.queryFormRef = ref)}
          show={form_show}
          option={searchOption}
          onGetValues={(values) => this.getData(values)}
          onReset={(values) => this.onReset(values)}
        ></TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() =>
            this.setState({ form_show: !this.state.form_show })
          }
          onTableRefresh={() => this.onTableRefresh()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton
            type={"primary"}
            size={"middle"}
            haspermi={["app:brand:add"]}
            onClick={() => {
              this.add();
            }}
          >
            新增品牌
          </TheButton>
        </TheTableExtend>

        <TheTable
          bordered
          loading={loading}
          dataSource={dataSource}
          columns={newColumns}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />


      </div>
    );
  }
}

export default AppBrandInfo;
